package com.xiweicheng.test.springboot.upload;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import lombok.extern.slf4j.Slf4j;

@SpringBootApplication
@RestController
@Slf4j
public class Application {

	String base = "/Users/xiweicheng/temp";

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

	@PostMapping("upload")
	public String upload(@RequestParam("file") MultipartFile file) {

//		try {
//			FileUtils.forceMkdir(new File(base + "/upload/"));
//			file.transferTo(new File(base + "/upload/" + UUID.randomUUID().toString() + ".tmp"));
//		} catch (IllegalStateException | IOException e) {
//			e.printStackTrace();
//			log.error(e.getMessage(), e);
//			return e.getMessage();
//		}

		try {
			FileUtils.copyToFile(file.getInputStream(),
					new File(base + "/upload/" + UUID.randomUUID().toString() + ".tmp"));
		} catch (IOException e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
			return e.getMessage();
		}

		return "ok";
	}
}
